<template>
 
	<view>
		<image src="http://qiniuapplet.jiachuangnet.com/baoxiao.png" class="bg"></image>
		<view class="container">
			<u-navbar title='申请报销' :autoBack="true" bgColor="transparent" left-icon-color="white"
				titleStyle="color:white"></u-navbar>
			<view class="info">
				<view class="margin20">
					<view class="margin20">
						<span style="color: red;">*</span>
						报销店铺
					</view>
					<view class="inputBorder" style="position:relative">
						<Search :dataSource="dataSource" @select="handleChange" placeholder="请输入门店名称" @search="checkStore"/>
            <u-input placeholder="请输入搜索内容" v-model='storeName' @input="onInput"> <template slot="suffix">
              <u-button v-if='storeName' @tap="getCode" text="收起" size="mini"></u-button>
            </template></u-input>
            <!-- 搜索结果列表 -->
            <view class="storeNameStyle">
							<span v-for="(item, index) in radioStoreList" :key="index"
								@click="checkStore(item)">{{ item.storeName }}</span>
						</view>
					</view>
				</view>
				
				<view class="margin20">
					<view class="margin20">
						<span style="color: red;">*</span>
						报销金额
					</view>
					<view class="inputBorder">
						<u-input v-model="money" placeholder="请输入报销金额"></u-input>
					</view>
				</view>
				<view class="margin20" @click="checkType">
					<view class="margin20">
						<span style="color: red;">*</span>
						报销类型
					</view>
					<view class="inputBorder">
						<u-input v-model="typeText" readonly placeholder="请选择报销类型"></u-input>
					</view>
				</view>
				<view class="margin20">
					<view class="margin20" style="display: flex;align-items: center;">
						<view>
							<span style="color: red;">*</span>
							收款方式
						</view>
						<view>
							<u-radio-group v-model="paymentType" placement="row" @change="paymentTypeGroupChange">
								<u-radio :customStyle="{marginLeft: '14px'}" v-for="(item, index) in paymentTypeList"
									:key="index" :label="item.name" :name="item.value">
								</u-radio>
							</u-radio-group>
						</view>
					</view>
					<view>
						<view v-if="paymentType=='1'">
							<view class="inputBorder margin20">
								<u-input v-model="cardNo" placeholder="请输入卡号"></u-input>
							</view>
							<view class="inputBorder margin20">
								<u-input v-model="bankName" placeholder="请输入开户行"></u-input>
							</view>
							<view class="inputBorder margin20">
								<u-input v-model="cardName" placeholder="请输入持卡人"></u-input>
							</view>
						</view>
						<view v-if="paymentType=='2'">
							<span>收款码</span>
							<u-upload style="margin-top: 15rpx;" :fileList="fileList1" @afterRead="afterRead"
								@delete="deletePic" name="1" :maxCount="1"></u-upload>
						</view>
						<view v-if="paymentType =='3'">
							<span>收款码</span>
							<u-upload style="margin-top: 15rpx;" :fileList="fileList2" @afterRead="afterRead"
								@delete="deletePic" name="2" :maxCount="1"></u-upload>
						</view>
					</view>
				</view>
				<view class="margin20">
					<view class="margin20">
						<span style="color: red;">*</span>
						报销凭证
					</view>
					<view>
						<u-upload :fileList="fileList3" @afterRead="afterRead" @delete="deletePic" name="3" multiple></u-upload>
					</view>
				</view>
				<view class="margin20">
					<view class="margin20">
						<span style="color: red;">*</span>
						费用说明
					</view>
					<view class="inputBorder">
						<u-input v-model="matter" placeholder="请输入内容"></u-input>
					</view>
				</view>
				<view class="margin20">
					<view class="margin20">
						备注
					</view>
					<view class="inputBorder">
						<u--textarea count v-model="remark" placeholder="请输入内容"></u--textarea>
					</view>
				</view>
			</view>
			<u-button type="primary" style='margin-top:20rpx' shape='circle' @click="comfirmForm">确定</u-button>
		</view>
		<u-picker :show="typeShow" :columns="columns" keyName="levelName" @cancel='close' @confirm='confrim'></u-picker>
		<u-notify ref="uNotify" message="hi"></u-notify>
	</view>
          


</template>

<script>
let app = getApp()
import Search from '@/components/search/index.vue'

export default {
  // components: {
  // 	Search
  // },
  // watch: {
  // 	storeName: {
  // 		handler(newVal, oldVal) {
  // 			if (!newVal) {
  // 				this.listStatus = false;
  // 			}
  // 		},
  // 		immediate: true
  // 	}
  // },
  data() {
    return {
      color: app.globalData.defaultColor,
      radioStoreName: '',
      paymentType: '银行卡',
      dateShow: false,
      money: null,
      cardNo: "",
      fileList1: [],
      fileList2: [],
      fileList3: [],
      storeName: '',
      cardName: "",
      matter: "",
      typeShow: false,
      typeText: '',
      remark: '',
      bankName: '',
      paymentMethod: "",
      proof: [],
      bankUserName: '',
      columns: [],
      fileUpload: [],
      listStatus: false,
      paymentTypeList: [{
        name: '银行卡',
        value: 1,
      },
        {
          name: '微信',
          value: 2,
        },
        {
          name: '支付宝',
          value: 3,
        }
      ],

      radioStoreList: [],
      searchQuery: "",
      dataSource: [],
    }
  },
  methods: {
    handleChange(data) {
      console.log(data)
    },
    stroeNameGroupChange() {
      this.listStatus = false;
      this.storeName = this.radioStoreName;
    },
    paymentTypeGroupChange(e) {
      this.paymentMethod = e
    },
    close() {
      this.typeShow = false;
    },
    // searchStoreName() {
    // 	uni.$u.debounce(this.toNext, 1000);
    // },
    // toNext() {
    // 	this.searchList = [];
    // 	this.listStatus = true;
    // 	// 此处调用searchList 模糊搜索
    // 	let params={
    // 		storeName:this.storeName
    // 	}
    // 	uni.$u.http.get('/order/getOrderInfoLikeName',{params:params}).then(res => {
    // 	 this.radioStoreList=res
    // 	})
    // },
    onInput(e) {
      this.searchQuery = e
      this.radioStoreList = [];
      if (this.searchQuery) {
        // 调用远程API进行搜索
        let params = {
          storeName: this.searchQuery
        }
        uni.$u.http.get('/order/getOrderInfoLikeName', {
          params: params
        }).then(res => {
          this.radioStoreList = res
        })
      } else {
        // 清空搜索结果
        this.radioStoreList = [];
      }
    },
    checkStore(val) {
      this.orderId = val.orderId
      this.storeName = val.storeName
      this.radioStoreList = []
    },
    confrim(e) {
      this.typeShow = false;
      this.typeText = e.value[0].levelName;
      this.financeLevelId = e.value[0].levelId
      this.financeId = e.value[0].financeId
    },
    checkType() {
      this.columns = []
      this.typeShow = true
      uni.$u.http.get('/storeLedger/getFinanceLevelTypeDto').then(res => {
        this.columns.push(res)
      })
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
      if (event.name == 3) {
        this.proof.splice(event.index, 1)
      }
    },
    // 新增图片
    // async afterRead(event) {
    // 	// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
    // 	let lists = [].concat(event.file)
    // 	let fileListLen = this[`fileList${event.name}`].length
    // 	lists.map((item) => {
    // 		this[`fileList${event.name}`].push({
    // 			...item,
    // 			status: 'uploading',
    // 			message: '上传中'
    // 		})
    // 	})
    // 	console.log(lists,"list");
    // 	for (let i = 0; i < lists.length; i++) {
    // 		const result = await this.uploadFilePromise(lists[i].url)
    // 		console.log(result,"result");
    // 		let item = this[`fileList${event.name}`][fileListLen]
    // 		this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
    // 			status: 'success',
    // 			message: '',
    // 			url: result
    // 		}))
    // 		fileListLen++
    // 	}

    // if (event.name == 1 || event.name == 2) {
    // 	this.payUrl = this.fileUpload.toString()
    // } else if (event.name == 3) {
    // 	this.proof.push(this.fileUpload.toString())
    // 	console.log(this.proof,"图片");
    // }
    // },
    async afterRead(event) {
      // 动态生成文件列表的属性名
      const fileListName = `fileList${event.name}`;

      // 如果file是数组（multiple为true），则直接使用；否则将其放入数组
      let fileLists = Array.isArray(event.file) ? event.file : [event.file];

      // 将每个文件添加到文件列表，并设置状态为'上传中'
      fileLists.forEach(item => {
        this[fileListName].push({
          ...item,
          status: '上传中',
          message: '上传中'
        });
      });


      // 遍历文件列表进行上传
      for (let i = 0; i < fileLists.length; i++) {
        // 使用await等待上传结果
        const result = await this.uploadFilePromise(fileLists[i].url);
        // 更新文件列表中的文件状态
        let itemIndex = this[fileListName].findIndex(file => file.url === fileLists[i].url);
        if (itemIndex !== -1) {
          this[fileListName][itemIndex] = {
            ...this[fileListName][itemIndex],
            status: 'success',
            message: '',
            url: result
          };
        }
        if (event.name == 1 || event.name == 2) {
          this.payUrl = this.fileUpload.toString()
        } else if (event.name == 3) {
          this.proof.push(this.fileUpload.toString())
        }
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: 'https://shelves.jiachuangnet.com/apidev/common/fileImgUrl', // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'file',
		  header: {
				'token': uni.getStorageSync('token')
			},
          formData: {
            user: 'test'
          },
          success: (res) => {

            setTimeout(() => {
              resolve(res.data.data)
              const data = JSON.parse(res.data);
              this.fileUpload = data.result
              console.log(data.result);
            }, 1000)
          }
        });
      })
    },
    comfirmForm() {
      if (this.paymentMethod == 1) {
        this.payUrl = ""
      } else if (this.paymentMethod == 2 || this.payType == 3) {
        this.cardNo = ""
        this.cardName = ""
        this.bankName = ""
      }
      if (!this.orderId) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请输入店铺名称',
        })
      }
      if (!this.money) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请输入报销金额',
        })
      }
      if (!this.financeId) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请选择报销分类！',
        })
      }
      if (!this.paymentMethod) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请选择付款方式！',
        })
      }
      if (this.paymentMethod == 1 && (!this.cardNo || !this.cardName || !this.bankName)) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请完善银行卡信息！',
        })
      }
      if (!this.proof) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请上传报销凭证！',
        })
      }
      if (!this.matter) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请填入报销费用说明！',
        })
      }
      if (this.paymentMethod != 1 && !this.payUrl) {
        return this.$refs.uNotify.show({
          top: 100,
          message: '请上传微信或支付宝付款码！',
        })
      }
      const data = {
        orderId: this.orderId,
        money: this.money,
        financeId: this.financeId,
        financeLevelId: this.financeLevelId,
        payUrl: this.payUrl || "",
        proof: this.proof || "",
        cardNo: this.cardNo,
        cardName: this.cardName,
        bankName: this.bankName,
        matter: this.matter,
        remark: this.remark,
        paymentMethod: this.paymentMethod,
		isClose: 1
      }
      uni.$u.http.post('/storeLedger/addStoreLedgerDetails', data).then(res => {
        if (res == 1) {
          this.$refs.uNotify.show({
            top: 100,
            type: 'success',
            message: '保存成功！',
          })
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/reimbursement/index"
            })
          }, 1000)

        }
      })
    },
    getCode() {
      this.radioStoreList = []
    }
  }
}
</script>
<style>
page {
  background-color: #f8f8f8;
}
</style>
<style lang="scss">
.bg {
  width: 750rpx;
  height: 440rpx;
  position: absolute;
  top: 0;
  left: 0;
}

.container {
  position: absolute;
  top: 200rpx;
  width: 700rpx;
  left: 25rpx;
  z-index: 100;
  padding-bottom: 100rpx;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.label {
  width: 130rpx;
}

.val {
  width: calc(100% - 150rpx);
}

.info {
  width: calc(100% - 50rpx);
  border-radius: 10rpx;
  background-color: white;
  padding: 25rpx;
}

.margin20 {
  margin-bottom: 30rpx;
}

.inputBorder {
  background-color: #f5f5f5;
  padding: 10rpx 0;
  border-radius: 10rpx;
}

.searchList {
  width: calc(100% - 40rpx);
  position: absolute;
  top: 80rpx;
  background: white;
  z-index: 1000;
  height: 300rpx;
  border: 1rpx solid #eee;
  padding: 20rpx;
  border-radius: 20rpx;
}

.info ::v-deep .u-radio {
  justify-content: space-between;
}

.info ::v-deep .u-textarea {
  background-color: transparent !important;
}

.storeNameStyle {
  max-height: 500rpx;
  overflow: auto;
  width: 100%;
  background-color: #F5F5F5;
  z-index: 10000;
  /* left: -2rpx; */
  border-radius: 15rpx;
  position: absolute;

  span {
    display: flex;
    margin-left: 50rpx;
    margin-top: 20rpx;
  }
}
</style>